//
//  DHTranslate.m
//  FurryCity
//
//  Created by 王大虎 on 2023/1/4.
//

#import "DHTranslate.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#import "NSData+Category.h"
#import "AFHTTPSessionManager.h"
// OTS webapi 接口地址
#define requestUrl @"https://itrans.xf-yun.com/v1/its"
// 应用ID（到控制台获取）
#define APPID @"0c734cbd"
// 接口APISercet（到控制台机器翻译服务页面获取）
#define APISecret @"MzAwMDljYmQ5NmYwZDc3MTBhZTIxYWE4"
// 接口APIKey（到控制台机器翻译服务页面获取）
#define APIKey @"ae7227d7b980bd1655f652a9ad6a738d"
// 语种列表参数值请参照接口文档：https://doc.xfyun.cn/rest_api/机器翻译.html
// 源语种
#define FROM @"en"
// 目标语种
#define TO @"cn"
// 翻译文本
#define TEXT @""
// 术语资源唯一标识，请根据控制台定义的RES_ID替换具体值，如不需术语可以不用传递此参数
#define RES_ID @"its_en_cn_word"
@implementation DHTranslate

static DHTranslate *_instance = nil;

+ (instancetype)sharedContext {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_instance == nil){
            _instance = [[DHTranslate alloc] init];
        }
    });
    return _instance;
}
-(void)translateFromENToCN:(NSString *)text success:(translateBlock)tran{
    NSDictionary *paramDic = [self buildParam:text];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",nil];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    manager.requestSerializer.timeoutInterval = 10.0f;
    manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
    
    
    [manager POST:[self buildRequetUrl] parameters:paramDic headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSDictionary *payload = responseObject[@"payload"];
        NSDictionary *result = payload[@"result"];
        NSString *text = result[@"text"];
        
        NSData *textData = [NSData dataWithBase64EncodedString:text];
        NSString *textStr = [[NSString alloc] initWithData:textData  encoding:NSUTF8StringEncoding];
        
        NSError * error = nil;
        NSData * getJsonData = [textStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
        
        NSDictionary *trans_result = getDict[@"trans_result"];
        NSString *dst = trans_result[@"dst"];
        if(tran){
            tran(dst);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
}

-(void)translateFromENToCN:(NSString *)text{
    
}


-(NSString *)buildRequetUrl{

    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"];
    dateFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    //设定时间格式,这里可以设置成自己需要的格式
    NSString *dateString = [dateFormatter stringFromDate:currentDate];//将时间转化成字符串

    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter2 setDateFormat:@"EEE,+dd+MMM+yyyy+HH:mm:ss+z"];
    dateFormatter2.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    dateFormatter2.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    //设定时间格式,这里可以设置成自己需要的格式
    NSString *dateString2 = [dateFormatter2 stringFromDate:currentDate];//将时间转化成字符串
    dateString2 = (__bridge NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef) dateString2,  NULL,CFSTR("!*'();:@&=$,/?%#[]"),
                                                          kCFStringEncodingUTF8);
    
    
    //hmacsha256加密原始字符串
    NSMutableString *builder = [[NSMutableString alloc]init];
    [builder appendString:@"host: "];
    [builder appendString:@"itrans.xf-yun.com"];
    [builder appendString:@"\n"];
    [builder appendString:@"date: "];
    [builder appendString:dateString];
    [builder appendString:@"\n"];
    [builder appendString:@"POST /v1/its HTTP/1.1"];
    
    NSString *sha = [self hmacSHA256WithSecret:APISecret content:builder];
    NSString *authorization_origin = [NSString stringWithFormat:@"api_key=\"%@\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"%@\"",APIKey,sha];
    
    NSData *authorization_origin_data = [authorization_origin dataUsingEncoding:NSUTF8StringEncoding];
    NSString *authorization = [authorization_origin_data base64EncodedString];
    NSString *host = @"itrans.xf-yun.com";
    

    NSString *url = [NSString stringWithFormat:@"%@?authorization=%@&host=%@&date=%@",requestUrl,authorization,host,dateString2];

    return url;
}



- (NSString *)hmacSHA256WithSecret:(NSString *)secret content:(NSString *)content {
    const char *cKey  = [secret cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [content cStringUsingEncoding:NSASCIIStringEncoding];
    //Sha256:
     unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                          length:sizeof(cHMAC)];
    NSString *hash = [HMAC base64EncodedString];//将加密结果进行一次BASE64编码。
    return hash;
}









// 组装请求参数
-(NSMutableDictionary *)buildParam:(NSString *)text{
    NSMutableDictionary *body = [[NSMutableDictionary alloc]init];
    NSMutableDictionary *header = [[NSMutableDictionary alloc]init];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    NSMutableDictionary *payload = [[NSMutableDictionary alloc]init];
    
    header[@"app_id"] = APPID;
    header[@"status"] = [NSNumber numberWithInt:3];
    header[@"res_id"] = RES_ID;
    
    NSMutableDictionary *its = [[NSMutableDictionary alloc]init];
    its[@"from"] = FROM;
    its[@"to"] = TO;
    its[@"result"] = [[NSMutableDictionary alloc]init];
    parameter[@"its"] = its;
    
    NSMutableDictionary *input_data = [[NSMutableDictionary alloc]init];
    input_data[@"encoding"] = @"utf8";
    input_data[@"status"] = [NSNumber numberWithInt:3];
    NSData *strData = [text dataUsingEncoding:NSUTF8StringEncoding];
    NSString *stringBase64 = [strData
                              base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithCarriageReturn];
    input_data[@"text"] = stringBase64;
    payload[@"input_data"] = input_data;
    
    body[@"header"] = header;
    body[@"parameter"] = parameter;
    body[@"payload"] = payload;
    
    return body;
}

@end
